package com.gzo.listen;

import com.alibaba.druid.pool.DruidDataSource;
import com.gzo.utils.SpringUtils;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

public class InitListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        DruidDataSource druidDataSource = (DruidDataSource) SpringUtils.getBean(DataSource.class);
        zookeeperDataChange(druidDataSource);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    private void zookeeperDataChange(final DruidDataSource dataSource) {
        //获取到zkClient
        final ZkClient zkClient = new ZkClient("192.168.95.121:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());
        zkClient.subscribeDataChanges("/zk-permanent", new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println("检查到数据库配置改变！");
                String url = zkClient.readData("/zk-permanent");
                String name = "root";
                String pwd = "123456";
                try {
                    dataSource.restart();
                    dataSource.setUrl(url);
                    dataSource.setUsername(name);
                    dataSource.setPassword(pwd);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });

    }


}
